﻿namespace FileStorageCenter.EFCore.Comparers;

public class CollectionValueComparer<TCollection, TModel> : ValueComparer<TCollection>
    where TCollection : IEnumerable<TModel>
{
    public CollectionValueComparer() : base(false)
    {

    }

    public override bool Equals(TCollection? left, TCollection? right)
    {
        return left is IEnumerable<TModel> v1 && right is IEnumerable<TModel> v2
            ? v1.SequenceEqual(v2)
            : base.Equals(left, right);
    }

    public override int GetHashCode(TCollection instance)
    {
        return instance is IEnumerable<TModel> v1
            ? v1.Aggregate(0, (a, v) => HashCode.Combine(a, v!.GetHashCode()))
            : base.GetHashCode(instance);
    }

    public override object? Snapshot(object? instance)
    {
        return instance is IEnumerable<TModel> v1
            ? v1.ToList()
            : base.Snapshot(instance);
    }
}